package com.know.web;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;

import my.mvc.RequestContext;
import my.util.ResponseUtils;

import org.apache.commons.lang.StringUtils;

import com.know.entity.Timeline;
import com.know.service.TimelineService;
import com.kzw.bean.Record;
import com.kzw.dao.support.Page;
import com.kzw.json.Jackson;



public class TimelineAction {
	private TimelineService timelineService=new TimelineService();
	
	/**
	 * 时间轴页面跳转服务界面
	 */
	public void into(RequestContext rc) throws ServletException, IOException {
		
		List<Timeline> list=timelineService.list();
		Map<String,Object> maps=timelineService.sort_list(list);
		rc.reqAttr("list", maps);
		System.out.println("跳转时间轴页面");
		rc.forward("/timeline.jsp");
	}
	/**
	 * 表格加载列表
	 * */
	public void talist(RequestContext rc) throws ServletException, IOException {
		int pageNo = rc.param("page", 1);
		int pageSize = rc.param("limit", 5);
		String orderBy = rc.param("orderBy", "");
		String orderDir = rc.param("orderDir", "");
		
		Page<Timeline> page = new Page<>(pageNo, pageSize);
		if(StringUtils.isNotBlank(orderBy)) {
			page.setOrderBy(orderBy);
			page.setOrder(orderDir);
		}
		
		Record record = timelineService.findPage(page);
		// 输出JSON
		String json = Jackson.me().toJson(record);
		//System.out.println(json);
		ResponseUtils.renderJson(rc.response(), json);
	}
	
		/**
	 * 根据标签ID读取（用于编辑）
	 */
	public void getone(RequestContext rc) throws ServletException,IOException{
		String id=rc.param("id");
		if(id!=null && !id.equals("")) {
			Timeline timelines = timelineService.findById(Long.parseLong(id));
			rc.reqAttr("timeline", timelines);
			rc.forward("/admin/timeline_form.jsp");
		}
	
	}
	/**
	 * 保存链接
	 */
	public void save(RequestContext rc) throws ServletException,IOException{
		// 将请求参数自动包装成Bean对象
		Timeline timeline = rc.form(Timeline.class);
	

			
		if(timeline.getTimeline_id()==0) {
			// 增加
			timelineService.save(timeline);
		} else {
			// 修改
			timelineService.update(timeline);
		}
		
		// 输出JSON
		String json = Jackson.me().toJson(new Record(true));
		ResponseUtils.renderJson(rc.response(), json);
		
	}
	/**
	 * 标签删除（待修改，检测是否关联文章）
	 * @throws IOException
	 */
	public void del(RequestContext rc) throws ServletException,IOException{
		long id = rc.param("id", 0L);

		Record record=timelineService.del(id);
		// 返回JSON
		String json = Jackson.me().toJson(record);
		ResponseUtils.renderJson(rc.response(), json);
	
	}
	/**
	 * 批量删除（待修改，检测是否关联文章）
	 * */
	public void multiDel(RequestContext rc) throws ServletException, IOException {
		String ids = rc.param("ids");
		Record record=new Record(false);
		if(StringUtils.isNotBlank(ids)) {
			record=timelineService.multiDel(ids);
			
		}		
		String json = Jackson.me().toJson(record);
		ResponseUtils.renderJson(rc.response(), json);
	}
}
